var express = require('express');
var app = express();

var catalog = require('./catalog.json');
var oldBibleContent = require('./old.json');
var newBibleContent = require('./new.json');

function keepInRange(num, min, max){
	return Math.max(min, Math.min(num, max));
}

// 仅处理 <= 99
function number2Chinese(num){
	if(num > 99){
		return '';
	}

	var arr = '一二三四五六七八九十'.split('');
	arr.unshift('');

	if(num <= 10){
		return arr[num];
	}else if(num < 20){
		return '十' + arr[num % 10];
	}else{
		return arr[parseInt(num / 10)] + '十' + arr[num % 10];
	}

}

app.get('/:book/:chapter/:section', function (req, res) {
	var book = req.params.book == 'old' ?  oldBibleContent : newBibleContent;

	var chapterIndex = keepInRange(Number(req.params.chapter), 0, book.chapters.length - 1);
	var chapter = book.chapters[chapterIndex];

	var sectionIndex = keepInRange(Number(req.params.section), 0, chapter.sections.length - 1);
	var section = chapter.sections[sectionIndex];

	res.json({
		name: book.name,
		chapter: {
			index: chapterIndex,
			count: book.chapters.length,
			order: '第' + number2Chinese(chapterIndex + 1) + '卷', // chapter 卷
			title: chapter.title,
		},
		section: {
			index: sectionIndex,
			count: chapter.sections.length,
			order: '第' + number2Chinese(sectionIndex + 1) + '章', // section 章
			content: section.content,
		}
	});
});

app.get('/catalog', function (req, res) {
	res.json(catalog);
});

app.all('/*', function (req, res) {
	res.status(404).send('Contents Not Found');
});

app.listen(3000);